package cn.victory.demo;

public class Snowflake {
    //工作中心ID
    private final long workerId;
    //数据中心ID
    private final long datacenterId;
    private long sequence = 0L;
    private long lastTimestamp = -1L;

    // 构造函数
    public Snowflake(long workerId, long datacenterId) {
        this.workerId = workerId;
        this.datacenterId = datacenterId;
    }

    // 生成ID的方法
    public synchronized long nextId() {
        long timestamp = System.currentTimeMillis();

        if (timestamp < lastTimestamp) {
            throw new RuntimeException("Invalid system clock!");
        }

        if (timestamp == lastTimestamp) {
            sequence = (sequence + 1) & 4095;
            if (sequence == 0) {
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            sequence = 0L;
        }

        lastTimestamp = timestamp;

        //自己定义一个雪花初始值795331200000L
        return ((timestamp - 795331200000L) << 22) |
                (datacenterId << 17) |
                (workerId << 12) |
                sequence;
    }

    // 等待下一毫秒的方法
    private long tilNextMillis(long lastTimestamp) {
        long timestamp = System.currentTimeMillis();
        while (timestamp <= lastTimestamp) {
            timestamp = System.currentTimeMillis();
        }
        return timestamp;
    }
}

